﻿using Common;
using Common.Extensions;
using Microsoft.AspNetCore.Mvc;
using Model;
using Model.DTO.User;
using System.Security.Claims;

namespace TianXiaHuiForumManagementSystem.Controllers.Public
{
    [Route("Api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly FileHelper _fileHelper;
        private readonly JWTHelper _jwtHelper;
        public FileController(FileHelper fileHelper, JWTHelper jwtHelper)
        {
            _fileHelper = fileHelper;
            _jwtHelper = jwtHelper;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost, Route("UploadFile")]
        public async Task<string> UploadFile(List<IFormFile> file)
        {
            var jsonUserInfo = _jwtHelper.TokenDecrypt("", ClaimTypes.UserData);
            if (string.IsNullOrWhiteSpace(jsonUserInfo))
            {
                return ResponseMessage.CreateError("没有上传权限").ToJsonFormat();
            }
            UserTokenDTO userTokenDTO = jsonUserInfo.ToObject<UserTokenDTO>() ?? new UserTokenDTO();
            if (userTokenDTO.Id <= 0)
            {
                return ResponseMessage.CreateError("没有上传权限").ToJsonFormat();
            }
            var result = await Task.Run(() => _fileHelper.UploadFile(file, userTokenDTO.Id));
            return ResponseMessage.CreateSuccess("上传完成", result).ToJsonFormat();
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet, Route("DownloadFile/{fileName}")]
        public async Task<ActionResult> DownloadFile(string fileName)
        {
            try
            {
                var fileStaream = await Task.Run(() => _fileHelper.DownloadFile(fileName));

                var contentType = FileHelper.GetContentType(fileName);

                return File(fileStaream, contentType);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
    }
}
